//
//  XLContributionViewController.m
//  XiangLove
//
//  Created by feng song on 2018/3/14.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLContributionViewController.h"
#import "XLContributionTableViewCell.h"
#import "XLHTTPSessionManager.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>
#import "XLCharmModel.h"
#import "XLPersonPageViewController.h"
#import "IMAChatViewController.h"
#import "NSString+Ext.h"

@interface XLContributionViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UITableView    *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) XLCharmModel   *CharmModel;
@property (nonatomic,strong) UIButton       *contriBtn;

@end

@implementation XLContributionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.fd_prefersNavigationBarHidden = YES;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self addTableView];
    [self addData];
}

-(void)addData
{
    [[[XLHTTPSessionManager sharedManager] GetUserConsumeRankUserId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        NSLog(@"贡献数据===%@",x);
        NSMutableArray *tempArray = self.modelArray.mutableCopy;
        [tempArray addObjectsFromArray:x];
        if (tempArray.count >0 && tempArray.count <=10) {
            self.modelArray = tempArray.copy;
        }else if (tempArray.count > 10)
        {
            for (int i = 0; i < 10; i++) {
                XLCharmModel * model = tempArray[i];
                [self.modelArray addObject:model];
            }
        }
        
        [self.tableView reloadData];
    } error:^(NSError *error) {
        
    }];
    
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(void)addTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, XQScreenW, XQScreenH-49) style:UITableViewStylePlain];
    _tableView.rowHeight = 86;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorColor = [UIColor clearColor];
    _tableView.allowsSelection = NO;
    [_tableView registerClass:[XLContributionTableViewCell class] forCellReuseIdentifier:NSStringFromClass([XLContributionTableViewCell class])];
    [self.view addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLContributionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLContributionTableViewCell class]) forIndexPath:indexPath];
    XLCharmModel *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.rankLabel.text = F(@"%zd", indexPath.row + 1);
    cell.nickNameLabel.text = model.NickName;
    CGFloat width = [cell.nickNameLabel.text sizeWidthsFont:16 andHeight:20];
    if (width > SCREEN_WIDTH - 120) {
        width =  SCREEN_WIDTH - 120;
    }
    width += 73;//加上头像和排行
    cell.levelImage.frame = CGRectMake(width, 24, 30, 14);
    [cell.levelImage setImageWithURL:[NSURL URLWithString:model.LevelIcon] placeholder:nil];

    cell.goldBeanLabel.text = F(@"昨日贡献%.0f累计贡献%.0f",[model.Money floatValue]*10,[model.TotalMoney floatValue]*10);
    cell.rankLabel.hidden = indexPath.row < 3;
    cell.rankImageView.hidden = indexPath.row > 3;
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        
        cell.privateState.hidden = NO;
        [cell.privateState addTarget:self action:@selector(goChatText:) forControlEvents:UIControlEventTouchUpInside];
        cell.privateState.tag = indexPath.row;
    }else{
        cell.privateState.hidden = YES;
    }
    [cell.privateState addTarget:self action:@selector(goChatText:) forControlEvents:UIControlEventTouchUpInside];
    cell.privateState.tag = indexPath.row;
    if (indexPath.row == 0) {
        cell.rankImageView.image = [UIImage imageNamed:@"conten_pic_shouhu1"];
        cell.avatarImageView.layer.borderColor = RGB_HEX(0xFDE1A1).CGColor;
        cell.nickNameLabel.textColor = RGB_HEX(0xFFE92F);
        cell.goldBeanLabel.textColor = RGB_HEX(0xFFC028);
    } else if (indexPath.row == 1) {
        cell.rankImageView.image = [UIImage imageNamed:@"conten_pic_shouhu2"];
        cell.avatarImageView.layer.borderColor = RGB_HEX(0x8FEEEF).CGColor;
        cell.nickNameLabel.textColor = RGB_HEX(0x8FEEEF);
        cell.goldBeanLabel.textColor = RGB_HEX(0x67BFC0);
    } else if (indexPath.row == 2) {
        cell.rankImageView.image = [UIImage imageNamed:@"conten_pic_shouhu3"];
        cell.avatarImageView.layer.borderColor = RGB_HEX(0xEFB588).CGColor;
        cell.nickNameLabel.textColor = RGB_HEX(0xEFB588);
        cell.goldBeanLabel.textColor = RGB_HEX(0xBD8A70);
    } else {
        cell.rankImageView.image = [UIImage imageNamed:@""];
        cell.nickNameLabel.textColor = RGB_HEX(0xffffff);
        cell.goldBeanLabel.textColor = RGB_HEX(0x9395A2);
        cell.avatarImageView.layer.borderColor = RGB_HEX(0xE6E6E6).CGColor;
    }
    return  cell;
}

-(void)goChatText:(UIButton *)sender
{
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"])
    {
        UIButton * chatText = sender;
        self.contriBtn = chatText;
        self.contriBtn.enabled = NO;
        [self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:0.5f];
        XLCharmModel *model = self.modelArray[chatText.tag];
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[model.UserId] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            DebugLog(@"vvvFailddd: %d->%@", code, msg);
        }];
        
    }
    
}

-(void)changeButtonStatus{
    self.contriBtn.enabled =YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
